package com.tenton.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName: RoutingTopicProducer
 * @Description： 4、路由订阅模式 生产者
 * @Author： tangdong
 * @Date： 2023/12/18
 */
public class RoutingTopicProducer {
    public static void main(String[] args) {
        //1、创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置IP
        connectionFactory.setHost("192.168.1.91");
        //设置端口
        connectionFactory.setPort(15672);
        //设置用户名
        connectionFactory.setUsername("td");
        //设置密码
        connectionFactory.setPassword("123456");
        //设置虚拟主机
        connectionFactory.setVirtualHost("/rabbit-routing");
        Connection connection = null;
        Channel channel = null;
        try {
            //2、创建连接
            connection = connectionFactory.newConnection();
            //3、创建通道
            channel = connection.createChannel();
            //声明交换机 参数1:交换机名称 参数2:交换机类型 基于指令的Routing key转发
            channel.exchangeDeclare("topics", "topic");
            //动态路由Key
            String key = "user.save";
            //发布消息
            channel.basicPublish("topics", key, null, ("这是路由中的动态订阅模型,routeKey：[" + key + "]的消息").getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
